<template>
  <f7-page>
    <qm-currentcy-navbar title="应用管理">
      <!-- <template #nav-right>
        <f7-icon f7="ellipsis"></f7-icon>
      </template> -->
    </qm-currentcy-navbar>
    <transition name="lyric">
    <div class="preservation" v-if="editing">
      <f7-row>
        <f7-col width="20"><f7-button outline small @click="cancel()">取消</f7-button></f7-col>
        <f7-col width="20"> <f7-button fill small @click="preservation()"> 保存</f7-button></f7-col>
      </f7-row>
    </div>
    </transition>
    <div class="out">
      <qm-block title="我的应用" :smtitle="editing?'（长按拖动排序）':''">
        <div>
        <draggable element="ul" v-model="commonly" class="qm-entry" :disabled="disabled" delay="500">
            <qm-entry-miniapp
            v-for="(item, index) in commonly"
            :key="index"
            :data="item"
            :parmas="parmas"
            :reduce="reduceEditing"
            :editing="editing"
            iconWidth="64"
            fontSize="24"
            @delete="deleteapp(item.serverId)"
          ></qm-entry-miniapp>
          </draggable>
        </div>
        <div class="title-footer" v-if="titlefooter">该区域最多可添加15个应用，超出的部分请先移除后再添加</div>
        <template v-slot:after-title v-if="!editing">
          <f7-button fill  small style="margin-right: 40px" @click="edit()">编辑</f7-button>
        </template>
      </qm-block>
      <qm-block
        :title="items.serverName"
        v-for="(items, index) in application"
        :key="index"
      >
        <div class="qm-entry">
          <qm-entry-miniapp
            v-for="(item, index) in items.children"
            :key="index"
            :data="item"
            :parmas="parmas"
            :plus="plusEditing"
            :myapp="commonly"
            :editing="editing"
            iconWidth="64"
            fontSize="24"
            @increase="appincrease"
          ></qm-entry-miniapp>
        </div>
      </qm-block>
    </div>
  </f7-page>
</template>

<script>
import draggable from 'vuedraggable'
export default {
    components: {
    //调用组件
    draggable,
  },
  data() {
    return {
      getUrl:
        "/api/app/mobileServer/getFunctionOptions",
      getFrequently:'/api/app/mobileServer/getFrequently',
      editapplication:'/api/app/mobileServer/serFrequently',
      appId: this.$f7.data.currentUser.userId,
      userCode: {
        userId: this.$f7.data.currentUser.userId,
        appCode: this.$f7.id || window.qmplus.runtime.appid,
        windowsId: this.$framework.account.getminiapphomepage().serverId,
      },
      // 显示添加过多文字
      titlefooter:false,
      // 显示加号
      plusEditing:false,
      // 显示减号
      reduceEditing:false,
      // 所有应用
      entry: [],
      // 常用应用
      commonly:[],
      // 是否处于编辑状态
      editing:false,
      // 是否禁止拖拽
      disabled:true,
      // 小程序解析参数
      parmas: JSON.parse(localStorage.getItem("miniapp_parmas") || "{}"),
      tips1:vue.$f7.toast.create({
        icon: `<i class="f7-icons">rays</i>`,
        text: "加载中",
        cssClass:'qm-toast',
        position: "center",
        closeTimeout: 10000,
      }),
    };
  },
  computed:{
    // 应用类型排序
    application(){
    return this.sortByKey(this.entry,'sort')
    },
  },
  methods:{
    // 对数据进行排序
  sortByKey(array, key) {
      array.forEach(item =>{
      if(item.children){
        this.sortByKey(item.children,'sort');
      }
      })
      return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];
        return x < y ? -1 : x > y ? 1 : 0;
      });
    },
    // 增加事件
    appincrease(data){
      this.commonly.push(data)
      if(this.commonly.length >= 15){
        this.plusEditing = false
        this.titlefooter=true
        return
      }
    },
    // 删减事件
    deleteapp(serverId){
      if(this.commonly.length < 2){
        this.reduceEditing === false
        this.$f7.dialog.confirm('至少需要保留一个应用')
        return
      }
      this.titlefooter=false
      this.plusEditing = true
      this.commonly.splice(this.commonly.findIndex(r=>r.serverId === serverId),1)
    },
    // 编辑
    edit(){
      this.reduceEditing=true
      this.editing=true
      this.disabled=false
      if(this.commonly.length >= 15){
        this.plusEditing = false
        this.titlefooter=true
        return
      }
        this.plusEditing=true
    },
    // 取消
    cancel(){
      this.getCommonlydata()
      this.reduceEditing=false
      this.plusEditing=false
      this.editing=false
      this.disabled=true
      this.titlefooter=false

    },
    // 保存
    preservation(){
      this.reduceEditing=false
      this.plusEditing=false
      this.editing=false
      this.disabled=true
      this.titlefooter=false
      let sort = {}
      sort.windowsId=this.$framework.account.getminiapphomepage().serverId
      sort.columns=[]
      let num = 1
      this.commonly.forEach((r)=>sort.columns.push({functionId:r.serverId,sort:num++}))
      // 发送请求
      this.$f7.request({
      url: this.editapplication,
      type: "POST",
      data: sort,
      async: true,
      cache: false,
      success:(result)=>{
        console.log('编辑成功');
      },error:(result)=>{

      }
      })
    },
    getalldata(){

      this.tips1.open()
      // 获取全部数据
      this.$f7.request.post(this.getUrl, this.userCode, (r) => {
        r = JSON.parse(r);
        if (r && r.success) {
          this.tips1.close()
          this.entry = r.data;
        } else {
          this.tips1.close()
          this.$f7.dialog.confirm("无法获取数据，请重新登录后尝试");
        }
      });
    },
    getCommonlydata(){
      this.tips1.open()
        // 获取常用数据
       this.$f7.request.post(this.getFrequently, this.userCode, (r) => {
        r = JSON.parse(r);
        if (r && r.success) {
          this.tips1.close()
          this.commonly = r.data;
        } else {
          this.tips1.close()
          this.$f7.dialog.confirm("无法获取数据，请重新登录后尝试");
        }
      });
    }
  },

  created() {
      this.getalldata()
      this.getCommonlydata()
  },
    destroyed(){
    this.tips1.close()
  }
};
</script>

<style lang="less" scoped>
.lyric-enter,
  .lyric-leave-to {
  opacity: 0;
  transform: translateY(10px);
  }
  .lyric-enter-to,
  .lyric-leave {
  opacity: 1;

  }
  .lyric-enter-active,
  .lyric-leave-active {
  transition: all 0.5s;
  }
/deep/.page-content {
  background-color: var(--color-fill-background) !important;
  padding-top: calc(88px * var(--ratio));
}
.preservation {
  background-color: #fff;
  width: 100%;
  padding: 5px 20px 20px;
}
.out {
  background-color: var(--color-fill-background);
  padding: 0;
  margin: 0;
  height: 100%;
  .title-footer{
    text-align: center;
    font-size: 12px;
    color: #8e8e93;
    margin-top: 10px;
  }
  .qm-block {
    background-color: var(--color-fill-grey-inverse);
    border: 1px solid var(--color-fill-grey-inverse);
    // border-radius: calc(16px * var(--ratio));
    margin: calc(20px * var(--ratio)) calc(0px * var(--ratio));
    padding-left: 0px;
    padding-right: 0px;
    /deep/.qm-block-title {
      margin-left: calc(32px * var(--ratio));
      font-size: var(--font-size-subtitle);
    }
    .qm-entry {
      display: grid;
      grid-template-columns: repeat(4, 25%);
      grid-row-gap: calc(30px * var(--ratio));
      /deep/.entry .entry-title {
        margin-top: calc(10px * var(--ratio));
      }
    }
  }
}
</style>
